<?php
namespace Helper;

use Core\Model;
use Core\TbRedis;
use Core\TanbaSwooleTable;

class GetLocationPoint{
    public $sysconfig;
    public function __construct(){


        $this->db =  new Model();
     // $this->redis =TbRedis:: tbredis();

        $myswoole_table= new TanbaSwooleTable();
        $this->sysconfig =$myswoole_table->sysconfig;

        $datas = $this->db->select('sysconfig', '*');
        if(!empty($datas)) {
            foreach ($datas as $data) {
                $this->sysconfig->set($data['key'], array('value' => $data['value']));
            }
        }

    }

    /**
     * 生成坐标
     * @date: 2017年11月18日 下午3:30:46
     * @author: ljn
     * @param:
     * @return:
     */
    public function setlocation($devid,$data,$type,$theRedis,$conn)
    {
        if (empty($data) ||  $type == 'AP') return false;

        $tbid = $data['tbid'];
        $devkey = $data['devkey'];
        $sendssi=$data['sendRssi'];

        $tbinfo=gettbinfo($tbid,$theRedis);
        $refdata = array(
            'tbid' => $tbid,
            'devtype' => $type,
            'devid' => $devid,
            'RSSI' => $data['realRssi'],
            'orssi' => $sendssi,
            'n' => $tbinfo['rn'],
            'dist' => $data['dist']
        );

        // echo  " \n tbid:" . $tbid . "," . $type . "[" . $devid . "]:" . $devkey . ",RSSI:" . $sendssi .",KMRssi:". $data['realRssi'].",KMdis:". $refdata['dist']." \n";
        echo ">";
        $theRedis->publish("Rssi_data_info_" . $type . "_" . $tbid, json_encode($refdata));//折线图数据

        $rdskey = "Loc_".$type . "_" . $devkey;
        $itemlist = $theRedis->hGetAll($rdskey);

        // 生成距离对应点集合
        if (isset($itemlist['hotpoint']) && !empty($itemlist['hotpoint'])) {
            $ht = json_decode($itemlist['hotpoint'], true);
            $tbcount = getCountHotPoint($ht);
            if ($tbcount > 0) {
                //删除过期的tbid-超过10s没有更新了
                $lcdh = $this->sysconfig->get('location_period', 'value');

                $otbid = getTbidFromHotPoint($ht, 'time', 'min');
                $mtinfo = getInfoHotPoint($otbid, $ht);

                if (($data['time'] - $mtinfo['time']) > (int)$lcdh)
                    $ht = delHotPoint($otbid, $ht);

                if (existHotPoint($tbid, $ht)) {
                    $oldht = getInfoHotPoint($tbid, $ht);

                    //限制频率 1秒钟1次的有效，太快的注意 // 5s钟之内的有效
                    $shtime = $this->sysconfig->get('rf_localtion_time', 'value');

                    if(($data['time'] - $oldht['time']) < (int)$shtime){
                        $ht = updateHotPoint($tbid, $ht, $data);
                    } else
                        return false;
                }
                else
                    $ht = newHotPoint($tbid, $ht, $data);
            } else
                $ht = newHotPoint($tbid, [], $data);


        } else
            $ht = newHotPoint($tbid, [], $data);

        $theRedis->hMset($rdskey, array('time'=>$data['time'],'hotpoint'=>json_encode($ht)));


        //--同时---接收到的先放一起,不同时间点的才计算
        if (!isset($itemlist['time']) || (isset($itemlist['time']) &&  $data['time'] <= $itemlist['time']))
               return false;


        //按照时间排序--最新的
        $theht = sortItemHotPoint($ht, 'time', 'SORT_DESC');

        $taskData = array(
            'type' => $type,
            'devid' => $devid,
            'time' => $data['time'],
            'hotpoint' => $theht
        );

        //  if (getCountHotPoint($ht) > 2) {
     //   echoMsg( "~".getCountHotPoint($ht)."~ \n",$theRedis);
        $this->GetLocationPoint($taskData, $theRedis,$conn); // 位置计算任务 taskwait

        //  }
    }
/*

$trilateration = new Trilateration();

$trilateration->setMiles(true);

$trilateration->setPoint1(22.549276,113.953776,  0.106);
$trilateration->setPoint2(22.549239, 113.953858,0.079);
$trilateration->setPoint3(22.549225,113.953835,0.080);

$point = $trilateration->getIntersectionPoint();

echo $point['lat'] . ', ' . $point['lng'];

-------------------------------------
也就是每相差1纬度，就当作y相差110千米，每相差1经度（假设在北京），相差85千米。

我们可以设置某一点为基点，
public static Tupe<double, double> GetGPSToXY(double latitude, double longitude)
{
    Tupe<double, double> r = new Tupe<double, double>();
    r.Item1 = (latitude - 40) * 110; //设 x 原点在 40 度。
    r.Item2 = (longitude - 116) * 85; //设 y 原点在 116 度。
    return r;
}



*/


    /**
     * 实时位置计算
     * @param $data
     * @param $Taskredis
     * @param $conn
     * Created by: xiebaoxin
     * Date: ${DATE}
     * Time: ${TIME}
     */
    private function GetLocationPoint($data,$Taskredis,$conn ) {

        if(empty($data)) return ;

        $type=$data['type'];
        $devid=$data['devid'];
        try{
            $loctiondatalant=0;
            $loctiondatalong=0;

            $trilateration = new Trilateration();

            $trilateration->setMiles(true);

            $ht=$data['hotpoint'];

            $newht=sortItemHotPoint($ht,'Rssi');
            $ik=0;
            $insert_data=array();
            foreach ($newht as $k => $vl) {
                $tbcfg=gettbinfo($k,$Taskredis);
                //  $vl['dist']=getDistancefromSdssi(array('rssi_n'=> $tbcfg['rn'],'realRssi'=>$vl['Rssi'],'rssi_a'=> $tbcfg['a0']));
                //   $insert_data[$k] =["id"=>$k,"type"=>$type,"devid"=>$devid,"x"=>$tbcfg['x'],"y"=>$tbcfg['y'],"z"=>$tbcfg['z'], "dist"=>$vl['dist'],"Rssi"=>$vl['Rssi']];
                /*
                                if($ik>=3){
                                    $objset="setPoint".$ik;
                                    $trilateration->$objset(floatval($tbcfg['latitude']),floatval($tbcfg['longitude']), floatval($vl['dist']/1000));
                                }
                */

                $loctiondatalant += floatval($tbcfg['latitude']);
                $loctiondatalong += floatval($tbcfg['longitude']);

                $ik++;
            }

            $loctiondata['lant']=$loctiondatalant/$ik;
            $loctiondata['long']=$loctiondatalong/$ik;

            /*

                                    $point = $trilateration->getIntersectionPoint();
                                    if(isset($point) ){
                                        $loctiondata['lant']=isset($point['lat'])?$point['lat']:$tbcfg['latitude'];
                                        $loctiondata['long']=isset($point['lng'])?$point['lng']:$tbcfg['longitude'];
                                    }


                                    //  $insert_data1=sortItemHotPoint($insert_data,'Rssi');
                                    $loctiondata= calculateLocation($insert_data);
                                    if(isset($loctiondata['triPtO']))
                                    {
                                        $loctiondata['triPtX']=$tbcfg['x'];
                                        $loctiondata['triPtY']=$tbcfg['y'];
                                        $loctiondata['triPtZ']=$tbcfg['z'];
                                    }
            */

            $loctiondata['devid']=$devid;
            $loctiondata['time']=date('Y-m-d H:i:s',$data['time']);
            $loctiondata['info']=$newht;

//一下先信号最强的作为地址
            $lasttbqyid=0;
            $loctiondata['addr']='';
            foreach ($newht as $ki => $vl) {
                $tbfg=gettbinfo($ki,$Taskredis);
                $loctiondata['addr']=isset($vl['addressinfo']) ? $vl['addressinfo']:'';
                if(isset($tbfg['areaid']) &&  !empty($tbfg['areaid']))
                    $lasttbqyid =$tbfg['areaid'];
                else
                    $lasttbqyid= $conn->get('device_basehome','areaid', ['Id'=>$vl['tbid']]);

                break;
            }

            $lasttbqy= $lasttbqyid >1 ? $conn->get("area_info",["parent_id","address"], ['id'=>$lasttbqyid]) :1;
            $loctiondata['addr']=$lasttbqy['parent_id'] >1 ? $conn->get("area_info","address", ['id'=>$lasttbqy['parent_id']]):$lasttbqy['address'];
            $loctiondata['addrAreaId']=$lasttbqy['parent_id'] >1 ? $lasttbqy['parent_id']:$lasttbqyid;
           // echo "&&".$loctiondata['addr']."&&&";
            //  $loctiondata['devinfo']=$insert_data;

            //  var_dump($loctiondata);
            echo "@".$devid;
          //  echoMsg( "@".$devid,$Taskredis);
            $result= $Taskredis->publish("location_data_".$type."_".$devid, json_encode($loctiondata)); // publish  lPush
            /*
                        if($type=='RF'){
                            $table='rflocaltion';
                            $insert_data['rfid']=$devid;
                            $this->rflocdata[] =$loctiondata;
                        }
                        elseif($type=='STA'){
                            $table='stalocaltion';
                            $insert_data['staid']=$devid;
                            $this->stalocdata[] =$loctiondata;
                        }
                        elseif($type=='AP'){
                            return false;
                        }else
                            return false;

                        //   $conn=Model::tbDB();
                        //   $result=$conn->insert($table, $type=='RF' ? $this->rflocdata :$this->stalocdata);

                    if(!$result){
                        $msg= "\n".' Location Task DB ERR:'."\n";
                        echoMsg( $msg,$Taskredis);
                        $serv->finish(' Location Task DB ERR:');
                    }
            */



        } catch (\RedisException $e) {
            echo " task redis is off! now try connecting…… \n";
            $Taskredis=TbRedis::tbredis();
        }

    }

    /**
     * 获取历史轨迹
     * @param $data
     * @param $Taskredis
     * @param $conn
     * Created by: xiebaoxin
     */
    public function GetLocationPointHistory($data,$theRedis,$conn,$fd ) {

        if(!isset($data) || empty($data) || empty($data['hotpoint'])) return ;
        $loctiondata=[];
        $type=$data['type'];
        $devid=$data['devid'];
        try{
            $loctiondatalant=0;
            $loctiondatalong=0;

            $newht=$data['hotpoint'];
            $ik=0;
            foreach ($newht as $k => $vl) {
                $tbcfg=$this->gettboldinfofromdb($k,$data['time'],$conn,$theRedis,$fd);
                $loctiondatalant += floatval($tbcfg['latitude']);
                $loctiondatalong += floatval($tbcfg['longitude']);

                $ik++;
            }

            $loctiondata['lant']=$loctiondatalant/$ik;
            $loctiondata['long']=$loctiondatalong/$ik;


            //信号最强的作为地址
            $lasttbqyid=0;
            $loctiondata['addr']='';
            foreach ($newht as $ki => $vl) {
                $tbfg=$this->gettboldinfofromdb($ki,$data['time'],$conn,$theRedis,$fd);
                $loctiondata['addr']=isset($vl['addressinfo']) ? $vl['addressinfo']:'';
                if(isset($tbfg['areaid']) &&  !empty($tbfg['areaid']))
                    $lasttbqyid =$tbfg['areaid'];
                else
                    $lasttbqyid= $conn->get('device_basehome','areaid', ['Id'=>$vl['tbid']]);

                break;
            }
            $lasttbqy= $lasttbqyid >1 ? $conn->get("area_info",["parent_id","address"], ['id'=>$lasttbqyid]) :1;
            $loctiondata['addr']=$lasttbqy['parent_id'] >1 ? $conn->get("area_info","address", ['id'=>$lasttbqy['parent_id']]):$lasttbqy['address'];
            $loctiondata['addrAreaId']=$lasttbqy['parent_id'] >1 ? $lasttbqy['parent_id']:$lasttbqyid;


            $loctiondata['devid']=$devid;
            $loctiondata['time']=date('Y-m-d H:i:s',$data['time']);
            $loctiondata['info']=$newht;

        }catch (\PDOException $e) {
            echoMsg( " database is off! \n",$conn,true);
        }

        return $loctiondata;
    }


    function gettboldinfofromdb($tbid,$time,$theDb,$theRedis,$fd){

        $tbloct= $theRedis->hGetAll("tboldinfo.".$fd.$tbid.$time);
        if(isset($tbloct) && isset($tbloct['latitude']) && isset($tbloct['addressinfo']) && !empty($tbloct['addressinfo']) ){
           return $tbloct;
        }

        $tbloction =$theDb->select("device_movelog", ["areaid","address(addressinfo)","longitude","latitude"], array("dvid"=>$tbid,'logtime[<=]'=>$time,'LIMIT' => 1));
        if(isset($tbloction) && !empty($tbloction[0]['areaid']) && !empty($tbloction[0]['address'])){
            $tbloct=$tbloction[0];//过去的位置点
        }else
        {
            $tbloction =$theDb->get("device_basehome", ["x","y","z","rn",'a0',"ax",'areaid',"addressinfo","longitude","latitude",'ismove'], array("dvid"=>$tbid));
            if(empty($tbloction)) {
                $tbloction['dvid'] = $tbid;
                $tbloction['areaid'] = 1;
                $tbloction['addressinfo']='未定义';
                $tbloction['longitude']=113.953688;
                $tbloction['latitude']=22.5494;
            }
            $tbloct=$tbloction;
        }

        $theRedis->hMset("tboldinfo.".$fd.$tbid.$time, $tbloct);

        return $tbloct;

    }


}

